package com.speily.study.provider.controller;

import com.speily.study.provider.entity.AccountA;
import com.speily.study.provider.rocketmq.RocketMQProducer;
import com.speily.study.provider.service.AccountAService;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;

/**
 * @Auther: SPL
 * @Date: 2019-07-09 13:14
 * @Description:
 */

@RestController
public class Testcontroller {

    /**
     * 注入消息生产者
     */
    @Autowired
    @Qualifier("rocketMQProducer")
    private RocketMQProducer mqProducer;

    @Autowired
    private AccountAService accountAService;

    /**
     * rocketmq-普通消息测试
     */
    @RequestMapping("/test")
    public Object testMsg() throws InterruptedException, RemotingException, MQClientException, MQBrokerException {

        //生产消息
        Message msg = new Message("TestTopic-01", "TAG-01", ("SpringMVC集成RocketMq,发送信息至【TestTopic-01(TAG-01)】").getBytes());
        SendResult result = mqProducer.getDefaultMQProducer().send(msg);

        return result;
    }

    /**
     * 消费
     * rocketmq-事物消息测试
     */
    @RequestMapping("/consume")
    public Object consumeMoney(String money) {

        //A 转账给 B
        //事物最终一致

        BigDecimal m = new BigDecimal(money);
        long accountId = 1l;

        try {

            accountAService.consume(m,accountId);

        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }
}


